<?php
/**
 * Created by PhpStorm.
 * User: HanSon
 * Date: 2016/9/2
 * Time: 12:06
 */

namespace App\Service;


use App\Model\TemplateRecord;
use Carbon\Carbon;
use EasyWeChat\Foundation\Application;

class WechatService
{

    /**
     * 获取微信实例
     *
     * @param null $option
     * @return Application
     */
    public function getApp($option = null)
    {
        $option = $option ? : config('wechat.account');

        return new Application($option);
    }

    /**
     * 获取管理员openid
     *
     * @return array|null
     */
    public function getAdmin()
    {
        return config('wechat.admin');
    }

    /**
     * 发送消息模板
     *
     * @param $data
     * @param $openIds
     * @param $templateName
     */
    public function sendNotice($data, $url, $openIds, $templateName)
    {
        if(is_string($openIds)){
            $openIds = [$openIds];
        }

        foreach ($openIds as $openId) {
            $templateRecord = [
                'open_id' => $openId,
                'template_id' => config('wechat.template.'.$templateName),
                'content' => json_encode($data),
            ];
            try{
                app('wechat')->notice->to($openId)->url($url)->template(config('wechat.template.'.$templateName))->andData($data)->send();
                TemplateRecord::create($templateRecord);
            }catch(\Exception $e){
                if (\App::environment('local')) {
                    TemplateRecord::create($templateRecord);
                }
            }
        }

    }

    /**
     * 系统异常警报
     *
     * @param $api
     * @param $exception \Exception
     * @param string $first
     */
    public function report($api, $exception, $first = '系统异常')
    {
        $app = app('wechat');
        if($admins =$this->getAdmin()){
            $data = [
                'first' => $first,
                'keyword1' => $api,
                'keyword2' => $exception->getMessage(),
                'keyword3' => Carbon::now()->toDateString(),
                'remark' => '请查明异常原因，及时处理'
            ];
            try{
                foreach ($admins as $openId) {
                    $app->notice->to($openId)->template(config('wechat.template.exception'))->andData($data)->send();
                }
            }catch(\Exception $e){

            }
        }
    }

}